package com.un.ebs.contract.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.un.ebs.contract.domain.*;
import com.un.ebs.contract.dto.*;
import com.un.ebs.contract.enums.ContractTypeEnum;
import com.un.ebs.contract.service.ContractService;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.util.*;
import com.un.ebs.inventory.domain.InventoryNoteTypeExt;
import com.un.ebs.inventory.enums.BusinessRelationTypeEnum;
import com.un.ebs.inventory.enums.InventoryTypeEnum;
import com.un.ebs.inventory.service.InventoryNoteTypeService;
import com.un.ebs.product.ProductConfigureCode;
import com.un.ebs.sys.service.ConfigureService;
import com.un.ebs.sys.service.EntService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * (Contract)表控制层
 *
 * @author liubo
 * @since 2020-07-05 18:05:55
 */
@RestController
@RequestMapping("contract")
@Api(value = "contract")
public class ContractController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private ContractService service;

    @Resource
    private EntService entService;

    @Resource
    private InventoryNoteTypeService inventoryNoteTypeService;

    @Resource
    private ConfigureService configureService;

    @PostMapping("add")
    @ApiOperation(value = "创建")
    public WebResult<String> add(@RequestBody @Validated ContractDto req) {
        return WebUtils.success(service.add(req));
    }

    @PostMapping("addByPurchaseOrder")
    @ApiOperation(value = "创建")
    public WebResult addByPurchaseOrder(@RequestBody @Validated PurchaseOrderToContractDto req) {
        service.addByPurchaseOrder(req);
        return WebUtils.success();
    }

    @PostMapping("createOemBomInventoryInNote")
    @ApiOperation(value = "创建", notes = "根据合同创建指定【库存业务类型】的BOM物料单据，默认【标准BOM物料】")
    public WebResult createOemBomInventoryInNote(@RequestParam String id, @RequestParam String noteTypeId, @RequestParam String warehouseId) {
        service.createOemBomInventoryInNote(id, noteTypeId, warehouseId);
        return WebUtils.success();
    }

    @PostMapping("update")
    @ApiOperation(value = "修改")
    public WebResult update(@RequestBody @Validated ContractDto req) {
        service.update(req);
        return WebUtils.success();
    }

    @PostMapping("change")
    @ApiOperation(value = "变更")
    public WebResult<String> change(@RequestBody @Validated ContractChangeDto req) {
        return WebUtils.success(service.change(req));
    }

    @PostMapping("delete")
    @ApiOperation(value = "删除，合同")
    public WebResult delete(@RequestParam String id) {
        service.delete(id);
        return WebUtils.success();
    }

    @PostMapping("deleteItemById")
    @ApiOperation(value = "删除，合同条目")
    public WebResult deleteItemById(@RequestParam String id) {
        service.deleteItemById(id);
        return WebUtils.success();
    }

    @PostMapping("submit")
    @ApiOperation(value = "提交")
    public WebResult submit(@RequestParam String id) {
        service.submit(id);
        return WebUtils.success();
    }

    @PostMapping("submitCancel")
    @ApiOperation(value = "提交")
    public WebResult submitCancel(@RequestParam String id) {
        service.submitCancel(id);
        return WebUtils.success();
    }

    @PostMapping("audit")
    @ApiOperation(value = "审核")
    public WebResult audit(@RequestParam String id) {
        service.audit(id);
        return WebUtils.success();
    }

    @PostMapping("auditCancel")
    @ApiOperation(value = "审核撤销")
    public WebResult auditCancel(@RequestParam String id) {
        service.auditCancel(id);
        return WebUtils.success();
    }

    @PostMapping("close")
    @ApiOperation(value = "关闭")
    public WebResult close(@RequestParam String id) {
        service.close(id);
        return WebUtils.success();
    }

    @PostMapping("closeAndDerive")
    @ApiOperation(value = "关闭并派生合同")
    public WebResult closeAndDerive(@RequestBody ContractCloseAndDeriveDto req) {
        service.closeAndDerive(req);
        return WebUtils.success();
    }

    @PostMapping("copyToFormal")
    @ApiOperation(value = "复制")
    public WebResult copyToFormal(@RequestParam String id) {
        service.copyToFormal(id);
        return WebUtils.success();
    }

    @PostMapping("writeOff")
    @ApiOperation(value = "核销", notes = "临时合同核销")
    public WebResult writeOff(@RequestParam String tempContractItemId, @RequestParam String formalContractId, @RequestParam double qty) {
        service.writeOff(tempContractItemId, formalContractId, qty);
        return WebUtils.success();
    }

    @PostMapping("writeOffCancel")
    @ApiOperation(value = "核销撤销")
    public WebResult writeOffCancel(@RequestParam String id) {
        service.writeOffCancel(id);
        return WebUtils.success();
    }

    @PostMapping("writeOffUpdate")
    @ApiOperation(value = "核销修改")
    public WebResult writeOffUpdate(@RequestParam String id, @RequestParam double qty) {
        service.writeOffUpdate(id, qty);
        return WebUtils.success();
    }

    @GetMapping("queryWriteOffView")
    @ApiOperation(value = "查询，有未核销的客户")
    public WebResult<List<ContractItemWriteOffView>> queryWriteOffView(@RequestParam String skuId, @RequestParam String tempContractCode, @RequestParam String formalContractCode) {
        return WebUtils.success(service.queryWriteOffView(skuId, tempContractCode, formalContractCode));
    }

    @GetMapping("queryNotWriteOffBusinessEnt")
    @ApiOperation(value = "查询，有未核销的客户")
    public WebResult<List<BusinessEntDto>> queryNotWriteOffBusinessEnt() {
        return WebUtils.success(service.queryBusinessEnt());
    }

    @GetMapping("queryBusinessEnt")
    @ApiOperation(value = "查询，有未核销的客户")
    public WebResult<List<BusinessEntDto>> queryBusinessEnt(@RequestParam(required = false) BusinessRelationTypeEnum type) {
        return WebUtils.success(service.queryBusinessEnt(type));
    }

    @GetMapping("queryBusinessEntBySaleFormalContract")
    @ApiOperation(value = "查询，正式销售合同")
    public WebResult<List<BusinessEntDto>> queryBusinessEntBySaleFormalContract() {
        return WebUtils.success(service.queryBusinessEntBySaleFormalContract());
    }

    @GetMapping("queryNotWriteOffByCustomer")
    @ApiOperation(value = "查询，未核销的临时合同")
    public WebResult<IPage<ContractTempNotWriteOffExt>> queryNotWriteOffByCustomer(@RequestParam(required = false) String skuCode, @RequestParam(required = false) String customerEntId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryNotWriteOffByCustomer(skuCode,customerEntId, pageSize, pageIndex));
    }

    @GetMapping("list")
    @ApiOperation(value = "查询，按类别查询合同")
    public WebResult<IPage<ContractExt>> query(@RequestParam(required = false) String searchText, @RequestParam(required = false) ContractTypeEnum type, @RequestParam(required = false) Boolean frameStatus, @RequestParam int pageSize, @RequestParam int pageIndex) {
        if (frameStatus == null) {
            return WebUtils.success(service.query(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), type, null, null, pageSize, pageIndex));
        } else {
            return WebUtils.success(service.query(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), type, frameStatus, null, pageSize, pageIndex));
        }
    }

    @GetMapping("listPurchaseContract")
    @ApiOperation(value = "查询，如果未指定frameStatus则默认为false，否则为true")
    public WebResult<IPage<ContractExt>> queryPurchaseContract(@RequestParam(required = false) String searchText, @RequestParam(required = false) Boolean frameStatus, @RequestParam int pageSize, @RequestParam int pageIndex) {
        if (frameStatus == null) {
            return WebUtils.success(service.query(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), ContractTypeEnum.Purchase, false, null, pageSize, pageIndex));
        } else {
            return WebUtils.success(service.query(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), ContractTypeEnum.Purchase, frameStatus, null, pageSize, pageIndex));
        }
    }

    @GetMapping("listPurchasePrice")
    @ApiOperation(value = "查询，采购价格列表")
    public WebResult<List<ContractItemExt>> queryPurchasePrice(@RequestParam String skuId) {
        return WebUtils.success(service.queryPurchasePriceList(skuId));
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "详情")
    public WebResult<ContractVo> queryById(@PathVariable String id) {
        return WebUtils.success(service.queryViewById(id));
    }

    @GetMapping("listItem/{id}")
    @ApiOperation(value = "明细，按合同ID查询")
    public WebResult<List<ContractItemExt>> queryItemById(@PathVariable String id) {
        return WebUtils.success(service.queryItemsById(id));
    }

    @GetMapping("listItemBySubsidiary")
    @ApiOperation(value = "明细，辅材")
    public WebResult<List<ContractItemExt>> queryItemBySubsidiary(@RequestParam String id) {
        return WebUtils.success(service.queryItemById(id, configureService.getValueByCode(ProductConfigureCode.other_spu_class_id)));
    }

    @GetMapping("listSaleFormal")
    @ApiOperation(value = "查询，正式销售合同")
    public WebResult<List<ContractExt>> querySaleFormal(@RequestParam String customerEntId, @RequestParam Integer pageSize, @RequestParam Integer pageIndex) {
        return WebUtils.success(service.querySaleFormal(customerEntId, pageSize, pageIndex));
    }

    @GetMapping("listItemByCode")
    @ApiOperation(value = "明细，按合同Code查询")
    public WebResult<IPage<ContractItemExt>> queryItemByCode(@RequestParam String code, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryItemByCode(code, pageSize, pageIndex));
    }

    @GetMapping("listItemBySku")
    @ApiOperation(value = "明细，按SKU查询")
    public WebResult<IPage<ContractItemExt>> queryItemBySku(@RequestParam String skuId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryItemBySku(skuId, pageSize, pageIndex));
    }

    @GetMapping("listSaleContract")
    @ApiOperation(value = "查询，核销后的合同明细")
    public WebResult<IPage<SaleContractExt>> querySaleContract(@RequestParam String searchText, @RequestParam ContractTypeEnum type, @RequestParam String customerId, @RequestParam String personnelId, @RequestParam String skuId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        if (type == null) {
            return WebUtils.success();
        }
        return WebUtils.success(service.querySaleContract(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), type, customerId, personnelId, skuId, pageSize, pageIndex));
    }

    @GetMapping("listSaleContractByCode")
    @ApiOperation(value = "查询销售合同，按合同号")
    public WebResult<List<SaleContractExt>> querySaleContractByCode(@RequestParam String ContractCode) {
        return WebUtils.success(service.querySaleContract(ContractCode));
    }

    @GetMapping("listSaleContractByCustomer")
    @ApiOperation(value = "查询，核销后的合同，按客户汇总")
    public WebResult<IPage<SaleContractByCustomerExt>> querySaleContractByCustomer(@RequestParam String searchText, @RequestParam String customerId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.querySaleContractByCustomer(StringUtils.isNullOrEmpty(searchText) ? null : searchText.trim(), customerId, pageSize, pageIndex));
    }

    @GetMapping("queryItemByFrameAndEnt")
    @ApiOperation(value = "明细，查询采购框架协议，按企业查")
    public WebResult<IPage<ContractItemExt>> queryItemByFrameAndEnt(@RequestParam(required = false) String searchText, @RequestParam String entId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryItemByFrameAndEnt(searchText, entId, pageSize, pageIndex));
    }

    @GetMapping("queryItemBySale")
    @ApiOperation(value = "明细，查询销售合同明细，按企业查")
    public WebResult<IPage<ContractItemBySaleExt>> queryItemBySale(@RequestParam(required = false) String searchText, @RequestParam String entId, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryItemBySale(searchText, entId, pageSize, pageIndex));
    }

    @GetMapping("queryWriteOffDetail")
    @ApiOperation(value = "临时合同核销明细")
    public WebResult<IPage<ContractItemWriteOffDetailExt>> queryWriteOffDetail(@RequestParam(required = false) String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.queryWriteOffDetail(searchText, pageSize, pageIndex));
    }

    @GetMapping("querySaleCanInvoice")
    @ApiOperation(value = "查询，未开完发票的销售合同")
    public WebResult<IPage<ContractExt>> querySaleCanInvoice(@RequestParam(required = false) String searchText, @RequestParam int pageSize, @RequestParam int pageIndex) {
        return WebUtils.success(service.querySaleCanInvoice(searchText, pageSize, pageIndex));
    }

    @GetMapping("querySaleContractRunItem")
    @ApiOperation(value = "查询，销售合同执行明细")
    public WebResult<List<ContractItemRunDto>> querySaleContractRunItem(@RequestParam String contractCode,@RequestParam(required = false) String skuCode) {
        return WebUtils.success(service.querySaleContractRunItem(contractCode,skuCode));
    }

    @GetMapping("printPurchaseContract")
    @ApiOperation("打印采购合同")
    public void printCheck(@RequestParam String id, HttpServletResponse response) {
        ContractVo contract = service.queryViewById(id);
        if (contract == null) {
            throw new BusinessEntityNotFoundException(id, "库存业务单据数据");
        }
        BeanUtils.copyProperties(entService.queryById(contract.getBusinessEntId()), contract);
        InventoryNoteTypeExt type = inventoryNoteTypeService.queryOneByType(InventoryTypeEnum.CONTRACT_PURCHASE);
        if (type == null) {
            return;
        }
        if (StringUtils.isNullOrEmpty(type.getPrintTemplate())) {
            return;
        }
        contract.setContractSumMoneyDesc(ChineseYuanUtil.convert(new BigDecimal(contract.getContractSumMoney()).setScale(2, RoundingMode.HALF_UP).toString()));
        contract.setContractSumMoneyTax(new BigDecimal(contract.getContractSumMoney()).multiply(new BigDecimal(1 + contract.getTaxRate())).setScale(2, RoundingMode.HALF_UP).doubleValue());
        contract.setContractSumMoneyTaxDesc(ChineseYuanUtil.convert(new BigDecimal(contract.getContractSumMoney()).multiply(new BigDecimal(1 + contract.getTaxRate())).setScale(2, RoundingMode.HALF_UP).toString()));
        ReportUtils.print(contract, contract.getItems(), type.getPrintTemplate(), response);
    }

//    @GetMapping("queryAuditWorkflowObject")
//    @ApiOperation(value = "明细，查询销售合同明细，按企业查")
//    public WebResult<IPage<ContractItemBySaleExt>> queryAuditWorkflowObject(@RequestParam String objectId, @RequestParam String nodeInstanceId) {
//        return WebUtils.success(service.queryWorkflowObject(objectId,nodeInstanceId));
//    }

//    @GetMapping("queryItemByQuality")
//    @ApiOperation(value = "明细，质保维修业务")
//    public WebResult<IPage<QualityContractItemExt>> queryItemByQuality(@RequestParam(required = false) String skuCode, @RequestParam(required = false) String entId, @RequestParam int pageSize, @RequestParam int pageIndex) {
//        return WebUtils.success(service.queryItemByQuality(skuCode, entId, pageSize, pageIndex));
//    }
}